package com.tzh.config.Filter;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * @Author tzh
 * @Date 202003
 * @sage Test
 * @Description 日志中增加traceId，若消息头中存在traceId，则取消息头中的Traceid，traceId必须小写
 */
@Component
public class LogbackFilter implements Filter {

    private static final String UNIQUE_ID = "traceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean bInsertMDC = false;
        try {
            bInsertMDC = insertMDC((HttpServletRequest) request);
            chain.doFilter(request, response);
        } finally {
            if (bInsertMDC) {
                MDC.remove(UNIQUE_ID);
            }

        }
    }

    private boolean insertMDC(HttpServletRequest request) {
        List<String> names = Collections.list(request.getHeaderNames());
        String uniqueId = null;
        boolean isExist = false;
        for (String name : names) {
            if (name.toLowerCase().equals(UNIQUE_ID.toLowerCase())) {
                uniqueId = request.getHeader(UNIQUE_ID.toLowerCase());
                isExist = true;
            }
        }
        if (!isExist) {
            UUID uuid = UUID.randomUUID();
            uniqueId = uuid.toString().replace("-", "");
        }
        MDC.put(UNIQUE_ID, uniqueId.toUpperCase());
        return true;
    }
}
